<!--复杂属性列表组件-->
<template>
  <div>
    <el-table
      class="publicTable"
      id="publicTableId"
      :data="newTableData"
      @selection-change="handleSelectionChange"
      style="overflow-y: scroll; border: 1px solid #e6ebf5"
      border
      v-loading="loading"
    >
      <el-table-column :show-overflow-tooltip="true">
        <template slot="header" slot-scope="{}" v-if="col.isReadOnly == 1 ? false : true">
          <el-row :gutter="5">
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-plus"
                size="mini"
                @click="handleAdd"
                >新增</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-delete"
                size="mini"
                :disabled="multiple"
                @click="handleDelete"
                >删除</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                >导出</el-button
              >
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="primary"
                plain
                icon="el-icon-upload2"
                size="mini"
                @click="handleImport"
                >导入</el-button
              >
            </el-col>
          </el-row>
        </template>
        <el-table-column :show-overflow-tooltip="true" label="操作" width="140" fixed="left" align="center">
          <template slot-scope="scope">
            <el-tooltip content="上移" placement="top" effect="light">
              <el-button type="text" size="mini" @click="upMove(scope.row)"> <i class="el-icon-top"></i></el-button>
            </el-tooltip>
            <el-tooltip content="下移" placement="top" effect="light">
              <el-button type="text" size="mini" @click="downMove(scope.row)">
                <i class="el-icon-bottom"></i
              ></el-button>
            </el-tooltip>
            <el-button type="text" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" type="index" label="NO." width="50"> </el-table-column>
        <el-table-column :show-overflow-tooltip="true" type="selection" width="35" align="center"> </el-table-column>
        <el-table-column v-if="columnsData.length == 0" width="520"> </el-table-column>
        <el-table-column
          v-else
          id="tableColumnId"
          :show-overflow-tooltip="true"
          v-for="(item, columindex) in columnsData"
          :key="columindex"
          :width="getWithNumber(columnsData, item.formwidth, 1)"
          :min-width="getWithNumber(columnsData, item.formwidth, 2)"
          :label="item.label"
          :prop="item.basicCode"
          :formatter="
            (row, column, cellValue) => formatter(cellValue, item.formTypeName, item.basicCode, item.dictList)
          "
        >
        </el-table-column>
      </el-table-column>
    </el-table>
    <pagination
      v-show="dataExtendTotal > 0"
      :total="dataExtendTotal"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getData"
    />

    <!-- 添加或修改文件对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      :close-on-click-modal="false"
      width="1200px"
      append-to-body
      class="extendForm"
    >
      <div>
        <el-form ref="extendEditForm" :model="form" :rules="rules" label-width="100px">
          <div class="fieldSetContent">
            <el-row :gutter="20">
              <el-col :span="col.span" v-for="(col, idx) in groupLayouts">
                <el-form-item
                  :label="col.label"
                  :prop="col.basicCode"
                  label-width="160px"
                  v-show="col.dataExtend !== true"
                  :rules="[{ required: col.jsRequired == 1 ? true : false, message: '不能为空', trigger: 'blur' }]"
                >
                  <!--col.formTypeName !== 'upload' &&-->
                  <!--单选select-->
                  <el-select
                    v-if="col.formTypeName === 'selectsingle'"
                    v-model="form[col.basicCode]"
                    :placeholder="'请选择' + col.label"
                    size="small"
                    :disabled="col.isReadOnly == 1 ? true : false"
                  >
                    <el-option
                      v-for="item in col.dictList"
                      :key="item.dictCode"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    ></el-option>
                  </el-select>
                  <!--多选select-->
                  <el-select
                    v-else-if="col.formTypeName === 'selectmulti'"
                    v-model="form[col.basicCode]"
                    multiple
                    :placeholder="'请选择' + col.label"
                    :disabled="col.isReadOnly == 1 ? true : false"
                  >
                    <el-option
                      v-for="item in col.dictList"
                      :key="item.dictCode"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    ></el-option>
                  </el-select>
                  <!--日期-->
                  <el-date-picker
                    v-model="form[col.basicCode]"
                    align="right"
                    type="date"
                    placeholder="选择日期"
                    :picker-options="pickerOptions"
                    v-else-if="col.formTypeName == 'date'"
                    :disabled="col.isReadOnly == 1 ? true : false"
                  >
                  </el-date-picker>
                  <!--日期时间-->
                  <el-date-picker
                    v-model="form[col.basicCode]"
                    v-else-if="col.formTypeName === 'datetime'"
                    type="datetime"
                    placeholder="选择日期时间"
                    align="right"
                    :picker-options="pickerOptions"
                    :disabled="col.isReadOnly == 1 ? true : false"
                  >
                  </el-date-picker>
                  <!--单选-->
                  <el-radio-group
                    v-else-if="col.formTypeName === 'radio'"
                    v-model="form[col.basicCode]"
                    :disabled="col.isReadOnly == 1 ? true : false"
                  >
                    <el-radio v-for="item in col.dictList" :label="item.dictValue">{{ item.dictLabel }}</el-radio>
                  </el-radio-group>
                  <!--checkbox-->
                  <el-checkbox-group
                    v-else-if="col.formTypeName === 'checkbox'"
                    v-model="form[col.basicCode] === null || form[col.basicCode] === undefined ? [] : form[col.basicCode]"
                    :disabled="col.isReadOnly == 1 ? true : false"
                  >
                    <el-checkbox v-for="item in col.dictList" :label="item.dictValue">{{ item.dictLabel }}</el-checkbox>
                  </el-checkbox-group>

                  <el-input-number
                    v-else-if="col.formTypeName === 'spinner'"
                    v-model="form[col.basicCode]"
                    :label="col.label"
                    :disabled="col.isReadOnly == 1 ? true : false"
                  ></el-input-number>

                  <UploadTable
                    v-else-if="col.formTypeName === 'upload'"
                    :col="col"
                    :partId="form['_id']"
                    :refType="col.uploadTypeId"
                    :fieldId="col.fieldId"
                    @change="fileListChange"
                  ></UploadTable>

                  <el-color-picker
                    v-else-if="col.formTypeName === 'color'"
                    v-model="form[col.basicCode]"
                    show-alpha
                    :predefine="predefineColors"
                    :disabled="col.isReadOnly == 1 ? true : false"
                  >
                  </el-color-picker>

                  <!--富文本-->
                  <editor
                    v-model="form[col.basicCode]"
                    v-else-if="col.formTypeName === 'richtext'"
                    :min-height="192"
                    :readOnly="col.isReadOnly == 1 ? true : false"
                  />

                  <el-input
                    type="textarea"
                    v-model="form[col.basicCode]"
                    v-else-if="col.formTypeName === 'textarea'"
                    :disabled="col.isReadOnly == 1 ? true : false"
                  ></el-input>
                  <el-input
                    v-else-if="col.formTypeName === 'input'"
                    v-model="form[col.basicCode]"
                    :placeholder="'请输入' + col.label"
                    :disabled="col.isReadOnly == 1 ? true : false"
                  />

                  <div v-else v-show="col.isReadOnly == 1 ? true : false">{{ col.formTypeName }}</div>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer" style="text-align: right">
          <el-button type="primary" @click="submitForm('extendEditForm')">确 定</el-button>
          <el-button @click="open = false">取 消</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog
      :title="upload.title"
      :visible.sync="upload.open"
      :close-on-click-modal="false"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsm"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        :show-file-list="true"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的数据
          </div>
          <span>仅允许导入xlsm格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <!-- <el-progress v-if="progressFlag" :percentage="loadProgress"></el-progress> -->
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listContainMCode } from '@/api/form/modelfield'
import {saveJson, getJson, getJsonById, editUpOrDown, delJsonById, newDataId} from '@/api/form/data'
import { getToken } from '@/utils/auth'
import UploadTable from '../UploadTable'

export default {
  name: 'publicTable',
  components: { UploadTable },
  props: {
    // 需要的参数
    col: {
      type: Object,
      required: true,
      default: () => {}
    },
    partId: {
      type: String,
      required: false,
      default: ''
    }
  },
  data() {
    return {
      loading: true,
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      // 知识库导入参数
      upload: {
        // 是否显示弹出层（知识库导入）
        open: false,
        // 弹出层标题（知识库导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的知识库数据
        updateSupport: 0,

        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/config/gridConfig/complexImport/' + this.col.fieldId + '/' + this.partId
      },
      originalTableData: [],
      newTableData: [],
      fieldId: '',
      dataExtendTotal: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },

      columnsData: [],
      //Linshi
      open: false,
      title: '',
      form: {},
      formModel: {},
      groupLayouts: [],
      // 选中数组
      ids: [],
      single: true,
      multiple: true,
      dataId: '',
      // 表单校验
      rules: {},
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      inputVisible: false,
      predefineColors: [
        '#ff4500',
        '#ff8c00',
        '#ffd700',
        '#90ee90',
        '#00ced1',
        '#1e90ff',
        '#c71585',
        'rgba(255, 69, 0, 0.68)',
        'rgb(255, 120, 0)',
        'hsv(51, 100, 98)',
        'hsva(120, 40, 94, 0.5)',
        'hsl(181, 100%, 37%)',
        'hsla(209, 100%, 56%, 0.73)',
        '#c7158577'
      ],
      uploadFields: []
    }
  },
  watch: {
    partId: {
      handler(n) {
        console.log('====dataExtend watch')
        console.log(n)
        this.getData()
      }
    }
  },
  created() {
    console.log('#####  dataExtend created')
    this.fieldId = this.col.fieldId
    this.originalTableData = this.tableData
    this.newTableData = this.tableData
    this.getList()
    this.getData()
  },
  methods: {
    // 当整个列宽加一起，比表格宽度小时，用min-width，当列宽度和相加大于格宽度时，用with 取实际的
    // type=1是要返回width的值，type=2是返回min-width的值
    getWithNumber(columnsData, formwidth, type) {
      let retWithVal = 0
      // 表格宽度
      let publicTableId = document.getElementById('publicTableId').offsetWidth

      // 列的总宽度
      let sumWidth = 0
      columnsData.map(item => {
        sumWidth = sumWidth + parseInt(item.formwidth)
      })
      if (type == 1 && sumWidth >= publicTableId) {
        retWithVal = formwidth
      }
      if (type == 2 && sumWidth < publicTableId) {
        retWithVal = formwidth
      }
      return retWithVal
    },
    // 上下移动
    // UP标识向上
    // DOWN表示向下
    upMove(row) {
      let tplId = this.fieldId
      let parentId = row._parent_id.id
      let id = row._id
      let type = 'UP'
      editUpOrDown(tplId, parentId, id, type).then(response => {
        if (response.code != 200) {
          this.$message({
            message: response.msg,
            type: 'error'
          })
        } else {
          this.getData()
        }
      })
    },
    downMove(row) {
      let tplId = this.fieldId
      let parentId = row._parent_id.id
      let id = row._id
      let type = 'DOWN'
      editUpOrDown(tplId, parentId, id, type).then(response => {
        if (response.code != 200) {
          this.$message({
            message: response.msg,
            type: 'error'
          })
        } else {
          this.getData()
        }
      })
    },
    getList() {
      // 查询属性code格式化后的列配置list
      listContainMCode({ parentId: this.fieldId }).then(data => {
        if (data.code === 200) {
          // 表列数据
          this.columnsData = data.data
          this.columnsData.forEach(r => {
            if (r.formTypeName === 'checkbox') {
              this.$set(this.formModel, r.basicCode, [])
            } else {
              this.$set(this.formModel, r.basicCode, null)
              if (r.formTypeName === 'upload') {
                this.uploadFields.push(r.basicCode)
              }
            }
          })
          if (this.partId !== '') {
            this.formModel['_parent_id'] = this.partId
          }
          this.formModel['_TPL'] = this.fieldId
          // 添加或修改文件对话框
          this.form = JSON.parse(JSON.stringify(this.formModel))
          //对话框中label
          this.groupLayouts = data.data
        }
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = '导入'
      this.upload.open = true
    },
    getData() {
      if (
        this.fieldId !== undefined &&
        this.partId !== undefined &&
        this.partId !== null &&
        this.fieldId.length > 0 &&
        this.partId.length > 0
      )
        this.queryParams.tplId = this.fieldId
      this.queryParams.parentId = this.partId
      getJson(this.queryParams).then(response => {
        this.newTableData = response.list
        this.dataExtendTotal = response.total
        this.loading = false
      })
    },
    handleClick(row) {
      console.log(row)
    },
    addRow() {
      this.newTableData.push({})
    },
    // 临时
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item._id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      newDataId().then(dataId => {
        this.form = JSON.parse(JSON.stringify(this.formModel))
        this.open = true
        this.title = '添加复杂属性'
        this.form._id = dataId //新增时生成记录id
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      let id = row._id
      // 编辑按钮 只能选择一个
      if (id.length === 1) {
        id = id[0]
      }
      getJsonById({ dataId: id }).then(response => {
        // 防止mongo中没有属性 会覆盖掉原属性 尤其tag和checkbox
        for (let of in this.form) {
          for (let nf in response.data) {
            if (of === nf) {
              this.form[of] = response.data[nf]
            }
          }
        }
        this.form['_id'] = response.data._id
        this.form['_parent_id'] = response.data._parent_id.id
        this.open = true
        this.title = '修改复杂属性'
      })
    },
    /** 提交按钮 */
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 保存复杂属性
          saveJson(this.form, this.fieldId, this.partId).then(response => {
            if (response.code === 200) {
              this.$message({
                message: '复杂属性报存成功！',
                type: 'success'
              })
              this.getData()
              this.open = false
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row._id || this.ids
      this.$modal.confirm('是否确认删除数据!').then(function () {
        delJsonById(ids)
        }).then(() => {
          this.getList()
          this.getData()
          this.$modal.msgSuccess('删除成功')
        }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      console.log(this.fieldId)
      console.log(this.partId)
      this.download(
        '/config/gridConfig/complexExport/' + this.fieldId + '/' + this.partId + '/' + true,
        {},
        `模板.xlsm`
      )
    },
    showInput() {
      this.inputVisible = true
    },
    tagClose(tag, list) {
      list.splice(list.indexOf(tag), 1)
    },

    handleInputConfirm(code) {
      let inputValue = this.form[code + '_InputValue']

      if (inputValue) {
        this.form[code].push(inputValue)
      }
      this.inputVisible = false
      this.form[code + '_InputValue'] = ''
    },
    /** 下载模板操作 */
    importTemplate() {
      console.log('importTemplate')
      this.download(
        '/config/gridConfig/importTemplate/' + this.col.fieldId + '/' + this.partId + '/' + false,
        {},
        `模板.xlsm`
      )
    },
    /**
     * 导出
     */
    submitFileForm() {
      this.$refs.upload.submit()
    },
    /**文件上传中处理 */
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    /**
     * 导出结果下载
     */
    handleFileSuccess(response, file, fileList) {
      console.log(response)
      if (response.code == 200) {
        this.upload.open = false
        this.upload.isUploading = false
        this.$refs.upload.clearFiles()
        this.$alert(
          "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
            response.msg +
            '</div>',
          '导入结果',
          { dangerouslyUseHTMLString: true }
        )
        this.getList()
        this.download('/config/gridConfig/importResults', {}, `模板.xlsm`)
      } else {
        this.upload.open = false
        this.upload.isUploading = false
        this.$refs.upload.clearFiles()
        this.$alert(
          "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
            response.msg +
            '</div>',
          '导入结果',
          { dangerouslyUseHTMLString: true }
        )
        this.getList()
      }
    },
    /** 文件列表值变更 */
    fileListChange(a) {
      let l = []
      a.list.forEach(c => {
        l.push({
          fileId: c.id,
          fieldId: a.fieldId
        })
      })
      this.form['_selfUploadFiles'] = l
    },
    formatter(cellValue, type, column, dictList) {


      if (cellValue === null || cellValue === undefined || cellValue.length === 0) return null
      if (dictList === undefined) {
        return cellValue
      }

      let v = ''
      if (cellValue instanceof Array) {
        dictList.forEach(d => {
          cellValue.forEach(c => {
            if (d.dictValue === c) {
              v = v === '' ? d.dictLabel : v + ',' + d.dictLabel
            }
          })
        })
      } else {
        dictList.forEach(d => {
          if (d.dictValue === cellValue) {
            v = d.dictLabel
          }
        })
      }
      return v
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-table--medium .el-table__cell {
  padding: 5px 0;
}

::v-deep .el-table-column--selection .cell {
  padding: 0;
}

::v-deep .el-table .cell.el-tooltip {
    min-width: 0;
}

.dataExtendTable table {
  width: 100% !important;
}

.extendForm .el-dialog__body {
  padding: 12px 20px !important;
  height: 80vh;
  overflow-y: auto;
}
</style>
